package rsa;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;

public class RsaDemo2 {
    public static void main(String[] args) throws NoSuchAlgorithmException {


        try {
            //获取密钥对
            KeyPair keyPair = RSAUtil.getKeyPair();
            //获取公钥
            PublicKey publicKey = keyPair.getPublic();
            //将公钥转化为base64用于传输
            System.out.println("公钥字符串");
            System.out.println(RSAUtil.byte2Base64(publicKey.getEncoded()));

            //明文
            String message = "this is some message, 123";
            System.out.println("明文："+message);
            //利用公钥加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes = cipher.doFinal(message.getBytes());
            //获取密文的base64
            String secMessage = RSAUtil.byte2Base64(bytes);
            System.out.println("密文");
            System.out.println(secMessage);


            //利用公钥加密
            Cipher cipher2 = Cipher.getInstance("RSA");
            cipher2.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes2 = cipher.doFinal(message.getBytes());
            //获取密文的base64
            String secMessage2 = RSAUtil.byte2Base64(bytes2);
            System.out.println("密文2");
            System.out.println(secMessage2);

            Cipher cipherDecoder = Cipher.getInstance("RSA");
            cipherDecoder.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
            String plainMessage =  new String(cipherDecoder.doFinal(RSAUtil.base642Byte(secMessage2)));
            System.out.println("重新获取明文");
            System.out.println(plainMessage);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
